package com.whilelife.Wachovia.account;

import java.io.BufferedReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;

/**
 * Created by IntelliJ IDEA.
 * User: Brent Merle
 * Date: Nov 3, 2011
 * Time: 4:14:46 PM
 */
public class Account {

  private static final DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
  private final String accountNumber;
  private final ArrayList<Transaction> transactions = new ArrayList<Transaction>();

  public Account(String number) {
    this.accountNumber = number;
  }

  public void parseData(final BufferedReader br, final int statementYear) throws IOException {
    String line;
    while ((line = br.readLine()) != null) {
      line = line.trim();
      if (line.equalsIgnoreCase("Deposits and Other Credits")) {
        transactions.addAll(Deposit.parseDeposits(br, statementYear));
      } else if (line.equalsIgnoreCase("Other Withdrawals and Service Fees")) {
        transactions.addAll(Withdrawal.parseWithdrawals(br, statementYear));
      } else if (line.equalsIgnoreCase("Checks")) {
        transactions.addAll(Check.parseChecks(br, statementYear));
      } else if (line.equalsIgnoreCase("Customer Service Information")) {
        break;
      }

    }
  }

  /*@Override
  public String toString() {
    return "com.whilelife.Wachovia.Account " + accountNumber + ":\nDeposits: " + Deposit.sumDeposits(transactions) + "\nWithdrawals: " + Withdrawal.sumWithdrawals(withdrawals);
  }*/

  public String toCSV() {
    StringBuilder sb = new StringBuilder();
    Collections.sort(transactions, new Transaction.TransactionComparator());
    for (Transaction t : transactions) {
      sb.append(accountNumber);
      sb.append(',');
      sb.append(df.format(t.getDate()));
      sb.append(',');
      sb.append(t.getValue());
      sb.append(',');
      sb.append(t.getDescription());
      sb.append('\n');
    }

    return sb.toString();

  }
}
